package com.ruoyi.framework.interceptor.loginInterceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.pay.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;


@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.expiration:86400000}")
    private long jwtExpiration;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/app/user/login") || requestURI.equals("/app/user/validate-token")) {
            return true;
        }

        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
            printResult(response, AjaxResult.error("请求中未包含token"));
            return false;
        }

        try {
            token = token.substring(7);
            Claims claims = JwtUtil.parseJWT(token);
            if (claims == null) {
                printResult(response, AjaxResult.error("token无效或已过期"));
                return false;
            }

            String redisToken = stringRedisTemplate.opsForValue().get("token-" + claims.get("phone"));
            if (redisToken == null) {
                printResult(response, AjaxResult.error("登录已失效"));
                return false;
            }
            if (!token.equals(redisToken)) {
                printResult(response, AjaxResult.error("token被篡改"));
                return false;
            }

            String redisKey = "token-" + claims.get("phone");
            Long ttl = stringRedisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
            if (ttl != null && ttl < 10 * 60) {
                stringRedisTemplate.expire(redisKey, jwtExpiration / 1000, TimeUnit.SECONDS);
            }

            AuthenticationContextHolder.setContext(claims.get("phone").toString());
            return true;
        } catch (Exception e) {
            printResult(response, AjaxResult.error("非法的token"));
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthenticationContextHolder.clearContext();
    }

    private void printResult(HttpServletResponse response, AjaxResult result) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            ObjectMapper objectMapper = new ObjectMapper();
            String messageResult = objectMapper.writeValueAsString(result);
            writer.print(messageResult);
        } catch (Exception e) {
            // 可以添加日志
        }
    }
}